package com.fly.show.api;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.fly.show.model.JsonResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 测试文件上传
 * 
 * @author 00fly
 * @version [版本号, 2022年12月5日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@RestController
@Api(tags = "测试文件上传-api")
@SuppressWarnings("rawtypes")
public class SubmitDataController
{
    Resource[] resources;
    
    @Autowired
    private RestTemplate restTemplate;
    
    @PostConstruct
    private void init()
    {
        try
        {
            resources = new PathMatchingResourcePatternResolver().getResources(ResourceUtils.CLASSPATH_URL_PREFIX + "data/pic/**/*.jpg");
        }
        catch (IOException e)
        {
            log.error(e.getMessage(), e);
        }
    }
    
    /**
     * 带MultipartFile post请求接口
     */
    @ApiOperation("测试MultipartFile")
    @PostMapping("/sendPost")
    public JsonResult<?> sendPost(MultipartFile multipartFile)
        throws IOException
    {
        String url = "http://127.0.0.1:8080/upload";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        Resource fileAsResource = new ByteArrayResource(multipartFile.getBytes())
        {
            @Override
            public String getFilename()
            {
                return multipartFile.getOriginalFilename();
            }
            
            @Override
            public long contentLength()
            {
                return multipartFile.getSize();
            }
        };
        MultiValueMap<String, Object> multipartRequest = new LinkedMultiValueMap<>();
        multipartRequest.add("file", fileAsResource);
        multipartRequest.add("id", "1");
        multipartRequest.add("name", "girl");
        multipartRequest.add("sex", "F");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(multipartRequest, headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, JsonResult.class);
        log.info("ResponseEntity={}", responseEntity);
        return responseEntity.getBody();
    }
    
    @ApiOperation("测试MultipartFile")
    @GetMapping("/to/upload2")
    public JsonResult<?> upload2()
        throws IOException
    {
        String url = "http://127.0.0.1:8080/upload2";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        int key = RandomUtils.nextInt(0, 2);
        switch (key)
        {
            case 0:
                File file = new ClassPathResource("data/pic/001.jpg").getFile();
                params.add("file", new FileSystemResource(file));
                break;
            case 1:
                String path = new ClassPathResource("data/pic/001.jpg").getPath();
                params.add("file", new FileSystemResource(path));
                break;
            default:
                params.add("file", new ClassPathResource("data/pic/001.jpg"));
                break;
        }
        params.add("id", "1");
        params.add("name", "girl");
        params.add("sex", "F");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, JsonResult.class);
        log.info("ResponseEntity={}", responseEntity);
        return responseEntity.getBody();
    }
    
    @ApiOperation("测试MultipartFile[]")
    @GetMapping("/to/upload3")
    public JsonResult<?> upload3()
        throws IOException
    {
        String url = "http://127.0.0.1:8080/upload3";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        Arrays.stream(resources).forEach(image -> {
            params.add("files", image);
            log.info("add file: {}", image.getFilename());
        });
        params.add("id", "1");
        params.add("name", "girl");
        params.add("sex", "F");
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        ResponseEntity<JsonResult> responseEntity = restTemplate.postForEntity(url, requestEntity, JsonResult.class);
        log.info("ResponseEntity={}", responseEntity);
        return responseEntity.getBody();
    }
    
}
